package tailfile

import (
	"github.com/sirupsen/logrus"
	"logsAgent/common"
)

type tailTaskMgr struct {
	tailTaskMap      map[string]*tailTask
	collectEntryList []common.CollectEntry
	confChan         chan []common.CollectEntry
}

var (
	ttMgr *tailTaskMgr
)

func Init(allConf []common.CollectEntry) (err error) {
	ttMgr = &tailTaskMgr{
		tailTaskMap:      make(map[string]*tailTask, 20),
		collectEntryList: allConf,
		confChan:         make(chan []common.CollectEntry),
	}
	for _, conf := range allConf {
		tt := newTailTask(conf.Path, conf.Topic)
		err = tt.Init()
		if err != nil {
			logrus.Errorf("create tailObj for path:%s failed err :%v", conf.Path, err)
		}
		logrus.Infof("create a tail task for path:%s success ", conf.Path)
		ttMgr.tailTaskMap[tt.path] = tt
		go tt.run()
	}
	go ttMgr.watch()
	return

}

func (t *tailTaskMgr) watch() {
	for {
		newConf := <-t.confChan
		logrus.Infof("get new conf from etcd,conf:%v,satrt manage tailTask..", newConf)
		for _, conf := range newConf {
			//1原来存在的任务不用动
			if t.isExist(conf) {
				continue
			}
			//2. 原来没有的就新建一个
			tt := newTailTask(conf.Path, conf.Topic)
			err := tt.Init()
			if err != nil {
				logrus.Errorf("create tailObj for path:%s failed, err:%v", conf.Path, err)
				continue
			}
			logrus.Infof("create a tail task for path:%s success", conf.Path)
			t.tailTaskMap[tt.path] = tt
			go tt.run()
		}
		//3.原来有的现在没有的要tailTask停掉
		//找出tailTaskMap中存在，
		for key, task := range t.tailTaskMap {
			var found bool
			for _, conf := range newConf {
				if key == conf.Path {
					found = true
					break
				}
			}
			if !found {
				logrus.Infof("the task collect path:%s need to stop", task.path)
				delete(t.tailTaskMap, key)
				task.cancel()
			}
		}
	}
}

func (t *tailTaskMgr) isExist(conf common.CollectEntry) bool {
	_, ok := t.tailTaskMap[conf.Path]
	return ok
}

func SendNewConf(newConf []common.CollectEntry) {
	ttMgr.confChan <- newConf
}
